package com.leetcode.q13;

import java.util.*;

/**
 * <p> description: desc</p>
 *
 * @author tanzc
 * @date 2022/3/30
 **/
public class RomanToInt {
    public int romanToInt(String s) {
        Map<Character, Integer> m = new HashMap<>();
        m.put('I', 1);
        m.put('V', 5);
        m.put('X', 10);
        m.put('L', 50);
        m.put('C', 100);
        m.put('D', 500);
        m.put('M', 1000);
        List<Character> list = new ArrayList<>(Arrays.asList('I', 'V', 'X', 'L', 'C', 'D', 'M'));
        List<Character> needjudge = new ArrayList<>(Arrays.asList('I', 'X', 'C'));
        int num = 0;

        int i = 0;
        while (i < s.length()) {
            Character c = s.charAt(i);
            if (needjudge.contains(c)) {
                if (i + 1 < s.length()) {
                    int k = list.indexOf(s.charAt(i + 1)) - list.indexOf(c);
                    if (k == 1 || k == 2) {
                        i++;
                        Character cd = s.charAt(i);
                        num += (m.get(cd) - m.get(c));
                    } else {
                        num += m.get(c);
                    }
                } else {
                    num += m.get(c);
                }
            } else {
                num += m.get(c);
            }
            i++;
        }
        return num;
    }
}
